#include <iostream>
#include <string>
#include <vector>
#include <boost/filesystem.hpp>
#include "util.hpp"

//存放HTML网页的目录
const std::string src_path = "data/input";
const std::string output = "data/raw_html/raw.txt";

typedef struct DocInFo{
    std::string title;   //标题 
    std::string content; //内容
    std::string url;     //文件在官网中的URL
}DocInfo_t;

//coust & 输入
//* 输出
//& 输入输出
bool EnumFile(const std::string &src_path, std::vector<std::string> *file_list);
bool ParseHtml(const std::vector<std::string> &file_list, std::vector<DocInfo_t> *results);
bool SaveHtml(const std::vector<DocInfo_t> &results,const std::string &output);


int main()
{
  std::vector<std::string> files_list;//放置文件名
  //递归的将html文件带路径保存到file_list,方便后期one by ony的文件读取
  if(!EnumFile(src_path, &files_list))
  {
      std::cerr << "enum file name error!" << std::endl;
      return 1;
  }
  
  
  //文件内容的读取分析 根据file_list读取并解析
  std::vector<DocInfo_t> results;
  if(!ParseHtml(files_list,&results))
  {
      std::cerr << "parse heml error" << std::endl;
      return 2;
  }


  //把解析后的文件内容写入到output中，/3作为文档分隔符
  if(!SaveHtml(results,output))
  {
      std::cerr << "sava html error" << std::endl;
      return 3;
  }


     return 0;
}


bool EnumFile(const std::string &src_path, std::vector<std::string> *files_list)
{
    //
    namespace fs = boost::filesystem;
    fs::path root_path(src_path);

    //判断src_path存不存在
    if(!fs::exists(root_path))
    {
        std::cerr << src_path << "not exisit" << std::endl;
        return false;
    }

    fs::recursive_directory_iterator end;
    for(fs::recursive_directory_iterator iter(root_path); iter != end; iter++)
    {
        //是否为正经文件
        if(!fs::is_regular_file(*iter))
        {
            continue;
        }
        //.path(是一个文件对象)
        if(iter->path().extension() != ".html")
        {
            continue;
        }

        //调试
        //std::cout << "debug" << iter->path().string() <<std::endl;

        //正经文件
        //string指向对象所代表的字符串
        files_list->push_back(iter->path().string());

    }
    return true;
}

static bool ParseTitle(const std::string &file, std::string *title)
{
    std::size_t begin = file.find("<title>");
    if(begin == std::string::npos)
    {
        return false;
    }
    std::size_t end = file.find("</title>");
    if(end == std::string::npos)
    {
        return false;
    }

    begin += std::string("<title>").size();
    if(begin > end)
    {
        return false;
    }
    *title = file.substr(begin, end - begin); 

    return true;
}

static bool ParserContent(const std::string &file, std::string *content)
{
    //寻找<>,同样是去标签动作,利用状态机
    enum status{
        LABLE,
        CONTENT
    };
    //每个html文件从<开始,需要去掉
    enum status s = LABLE;
    for(char c : file)
    {
        switch(s)
        {
            case LABLE:
              {
                if(c == '>')
                {
                    s = CONTENT;
            
                }
                break;
              }
            case CONTENT:
            {
                if(c == '<')
                {
                    s = LABLE;
                }
                else
                {
                    if(c == '\n')
                    {
                         c = ' ';
                    }
                    content->push_back(c);
                }
                break;
            }

            default:
                break;
        }
    }
    return true;
}

static bool ParseUrl(const std::string &file_path, std::string *url)
{
    //官网下的查询路径
    std::string url_head = "https://www.boost.org/doc/libs/1_81_0/doc/html";
    //项目中的路径
    std::string url_tail = file_path.substr(src_path.size());

    *url = url_head + url_tail;
    return true;
}

//调试函数
static void ShowDoc(const DocInfo_t &doc)
{
    std::cout << "title: " << doc.title << std::endl;
    std::cout << "content: " << doc.content << std::endl;
    std::cout << "url :" << doc.url << std::endl;
}
bool ParseHtml(const std::vector<std::string> &files_list, std::vector<DocInfo_t> *results)
{
    for(const std::string &file: files_list)
    {
        std::string result;
        //读取
        if(!ns_util::FileUtil::ReadFile(file,&result))
        {
            continue;
        }
        DocInfo_t doc;
        //解析:去标签
        if(!ParseTitle(result,&doc.title))
        {
            continue;
        }
        //提取content
        if(!ParserContent(result,&doc.content))
        {
            continue;
        }
        //文件路径
        if(!ParseUrl(file, &doc.url))
        {
            continue;
        }

        //完成解析,且保存在doc
        //results->push_back(doc);//拷贝效率问题
        results->push_back(std::move(doc));

        //测设
        //ShowDoc(doc);
        //break;
    }
    return true;
}
bool SaveHtml(const std::vector<DocInfo_t> &results, const std:: string &output)
{
#define SEP '\3';
//二进制打开
    std::ofstream out(output, std::ios::out | std::ios::binary);
    if(!out.is_open())
    {
        std::cerr << "fail:" << output << "open fail" << std::endl;
        return false;
    }
    //开始写入
    for(auto &ite : results)
    {
        std::string out_string;
        out_string = ite.title;
        out_string += SEP;
        out_string += ite.content;
        out_string += SEP;
        out_string += ite.url;
        out_string += '\n';
        out.write(out_string.c_str(),out_string.size());
    }

    out.close();

    return true;
}
